import { useState, useEffect, useRef } from "react";
import { Skeleton, Button } from "antd";
import { DownloadOutlined } from "@ant-design/icons";
import { observer } from "Mobx-react";
import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
import { surveyStore } from "@/stores/survey";
import { processAnalysisData, onFill } from "@/computed/api";
import type { analysisType, answerType } from "@/types/index";
import { typeEnum } from "@/assets/common/enums";
import Screen from "../components/Screen";
import AnalysisTable from "../components/AnalysisTable";
import CheckText from "../components/CheckText";
import { AnalysisCard } from "../stye";

function Analysis() {
  const [loading, setLoading] = useState(false);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [dateList, setDate] = useState(["", ""]);
  const [dataInfo, setDataInfo] = useState({ titleText: "", endTime: "", startTime: "", assessCount: 0 });
  const [topicData, setTopicData] = useState<analysisType[]>([]);
  const checkRef = useRef<any>();

  const queryData = async (date: string[], condition: string, answer: answerType[]) => {
    setLoading(true);
    let { title, count, start, end, data } = await processAnalysisData(surveyStore.surveyId, date, condition, answer);
    setDataInfo({ titleText: title, endTime: end, startTime: start, assessCount: count });
    setTopicData([...data]);
    setLoading(false);
  };
  const onScreenQuery = async (date: string[], condition: string, answer: answerType[]) => {
    setDate(date);
    await queryData(date, condition, answer);
  };
  useEffect(() => {
    queryData(dateList, "and", []);
  }, [surveyStore.surveyId]);
  //下载报告
  const exportclick = () => {
    setDownloadLoading(false);
    let docxsrc = "/data.docx"; //模板文件的位置
    console.log("topicData", topicData);
    let queryStepListData = topicData.map(item => {
      let topicShow = true;
      let typeShow = true;
      if (item.type === typeEnum.PARAGRAPH) {
        topicShow = false;
        item.title = item.title.replace(/<[^>]+>/g, "");
      } else if (item.type === typeEnum.FILL) {
        typeShow = false;
      }
      return {
        topicShow,
        typeShow,
        title: item.title,
        type: item.type,
        option: item.option,
        assessCount: item.assessCount
      };
    });
    const data = {
      form: {
        title: dataInfo.titleText
      },
      list: queryStepListData
    };
    // 读取并获得模板文件的二进制内容
    JSZipUtils.getBinaryContent(docxsrc, function (error: any, content: any) {
      // docxsrc是模板。我们在导出的时候，会根据此模板来导出对应的数据
      // 抛出异常
      if (error) {
        throw error;
      }
      // 创建一个PizZip实例，内容为模板的内容
      let zip = new PizZip(content);
      // 创建并加载docx templater实例对象
      let doc = new docxtemplater().loadZip(zip);
      // 设置模板变量的值
      doc.setData({
        ...data.form,
        list: data.list
      });
      try {
        // 用模板变量的值替换所有模板变量
        doc.render();
      } catch (error: any) {
        // 抛出异常
        let e = {
          message: error.message,
          name: error.name,
          stack: error.stack,
          properties: error.properties
        };
        console.log(
          JSON.stringify({
            error: e
          })
        );
        throw error;
      }
      // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
      let out = doc.getZip().generate({
        type: "blob",
        mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      });
      // 将目标文件对象保存为目标类型的文件，并命名
      saveAs(out, dataInfo.titleText);
      setDownloadLoading(false);
    });
  };
  return (
    <AnalysisCard>
      <Screen onScreenQuery={onScreenQuery}></Screen>
      <Skeleton active paragraph={{ rows: 10 }} loading={loading}>
        <div className="analysis-title">{dataInfo.titleText}</div>
        {dataInfo.startTime && (
          <div className="analysis-column flex-between align-items">
            <div className="step-info">
              <span>
                答题时间：{dataInfo.startTime} 到 {dataInfo.endTime}
              </span>
              <span>测评量：{dataInfo.assessCount}</span>
            </div>
            <Button type="primary" icon={<DownloadOutlined />} loading={downloadLoading} onClick={exportclick}>
              进度报告
            </Button>
          </div>
        )}
        {topicData.map(item => (
          <div className="analysis-item" key={item.id}>
            {item.type !== typeEnum.PARAGRAPH ? (
              <>
                <div className="analysis-item-title">
                  {item.title} <span>[{item.type}]</span>
                </div>
                {onFill(item.type) ? (
                  <AnalysisTable tableData={item}></AnalysisTable>
                ) : (
                  <Button type="primary" onClick={() => checkRef.current?.open(item.title, item.fill)}>
                    详细作答情况
                  </Button>
                )}
              </>
            ) : (
              <div className="analysis-item-html" dangerouslySetInnerHTML={{ __html: item.title }}></div>
            )}
          </div>
        ))}
      </Skeleton>
      <CheckText ref={checkRef}></CheckText>
    </AnalysisCard>
  );
}

export default observer(Analysis);
